package com.aoxon.cargo.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.activity.n.PurMapActivity;
import com.aoxon.cargo.bean.District;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.GetCityService;
import com.aoxon.cargo.service.GetMarketService;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.SearchSupplierTipsService;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.DisplayUtil;
import com.google.gson.reflect.TypeToken;

/**
 * 采购端搜索商圈
 * 
 * @author ZZJ
 * 
 */
public class PurSupplierSearchActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	private ImageView ivReturnButton;
	private ImageView ivGPSButton;
	private TextView tvTitle;

	private EditText etSearchText;

	private LinearLayout llSearchSupTip;
	private LinearLayout llSearchSupCity;
	private LinearLayout llSearchSupMarket;
	private LinearLayout llWordSort;
	private ScrollView svSearchSupMarket;

	private int loadType = 0;
	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private String strSearchText = new String();
	private String cityString = new String();

	private List<String> tips = new ArrayList<String>();
	private List<District> cityDistricts = new ArrayList<District>();
	private List<District> marketDistricts = new ArrayList<District>();

	private int width;

	private SearchSupplierTipsService searchSupplierTipsService = (SearchSupplierTipsService) MyServiceFactory
			.getInstance(MyServiceFactory.SEARCH_SUPPLIER_TIPS);
	private GetCityService getCityService = (GetCityService) MyServiceFactory
			.getInstance(MyServiceFactory.GET_CITY);
	private GetMarketService getMarketService = (GetMarketService) MyServiceFactory
			.getInstance(MyServiceFactory.GET_MARKET);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		DisplayMetrics metric = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metric);
		width = metric.widthPixels; // 屏幕宽度（像素）

		setup();
	}

	private void setup() {
		setContentView(R.layout.pur_search_supplier);

		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivGPSButton = (ImageView) findViewById(R.id.ivPublicTitleOther);
		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);

		etSearchText = (EditText) findViewById(R.id.etPublicSearchText);

		llSearchSupTip = (LinearLayout) findViewById(R.id.llPurSearchSupTip);
		llSearchSupCity = (LinearLayout) findViewById(R.id.llPurSearchSupCity);
		llSearchSupMarket = (LinearLayout) findViewById(R.id.llPurSearchSupMarket);
		llWordSort = (LinearLayout) findViewById(R.id.llWordSort);
		svSearchSupMarket = (ScrollView) findViewById(R.id.svPurSearchMarket);

		ivGPSButton.setImageResource(R.drawable.button_gps);
		tvTitle.setText("选择商圈");
		etSearchText.setHint(" 请输入商圈名称");
		initWordSort();

		normalDataLoader.setOnloadDataListener(this);

		ivGPSButton.setOnClickListener(ivGPSclick);
		ivReturnButton.setOnClickListener(myClickListener);
		etSearchText.addTextChangedListener(myTextWatcher);

		// 设置图片的高度为图片的宽度
		LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) etSearchText
				.getLayoutParams();
		params.width = width - DisplayUtil.dip2px(this, 78);
		etSearchText.setLayoutParams(params);

		RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams) svSearchSupMarket
				.getLayoutParams();
		params2.width = width - DisplayUtil.dip2px(this, 100);
		svSearchSupMarket.setLayoutParams(params2);

		loadType = 1;
		normalDataLoader.load();

	}

	/**
	 * 显示搜索提示
	 */
	private void showTip() {
		for (int i = 0; i < tips.size(); i++) {
			final String tip = tips.get(i);
			View tipItem = getLayoutInflater().inflate(
					R.layout.pur_search_tip_text, null);
			TextView textView = (TextView) tipItem
					.findViewById(R.id.tvPurSearchGoodsTip);
			textView.setText(tip);

			tipItem.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getBaseContext(),
							PurSupplierSearchShowActivity.class);
					Bundle data = new Bundle();
					data.putBoolean("searchFormText", true);
					data.putString("searchText", tip);
					intent.putExtras(data);
					startActivity(intent);
				}
			});

			llSearchSupTip.addView(tipItem);

		}
	}

	private void initWordSort(){
		OnClickListener tvOnClick = new OnClickListener(){
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				Log.v("llwordSort", ((TextView)view).getText().toString());
			}
		};
		for(int i =0 ; i< 26 ;i++){
			char a = 'A';
			LayoutInflater inflater = LayoutInflater.from(this);
			View content = inflater.inflate(R.layout.word_sort_item, null);
			TextView tvWord = (TextView) content.findViewById(R.id.tvWord_word_sort);
//			TextView tvWord = (TextView) inflater.inflate(R.layout.word_sort_item, null);
			tvWord.setText(String.valueOf((char)(a+i)));
			tvWord.setOnClickListener(tvOnClick);
			llWordSort.addView(content);
		}
		
	}
	
	private void showCity() {

		for (int i = 0; i < cityDistricts.size(); i++) {
			final String strCity = cityDistricts.get(i).getDistrict();
			LinearLayout cityItem = (LinearLayout) getLayoutInflater().inflate(
					R.layout.pub_place_text, null);
			TextView textView = (TextView) cityItem
					.findViewById(R.id.tvPubPlaceMain);
			textView.setText(strCity);

			textView.setOnTouchListener(new OnTouchListener() {

				@Override
				public boolean onTouch(View arg0, MotionEvent arg1) {
					// TODO Auto-generated method stub
					llSearchSupTip.setVisibility(View.GONE);
					return false;
				}
			});
			textView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					cityString = strCity;
					svSearchSupMarket.setVisibility(View.VISIBLE);
					llSearchSupMarket.removeAllViews();
					marketDistricts.clear();
					loadType = 2;
					normalDataLoader.load();
				}
			});

			cityItem.removeAllViews();
			llSearchSupCity.addView(textView);
		}
	}

	private void showMarket() {
		for (int i = 0; i < marketDistricts.size(); i++) {
			LinearLayout marketItem = (LinearLayout) getLayoutInflater()
					.inflate(R.layout.pub_place_text, null);
			TextView textView = (TextView) marketItem
					.findViewById(R.id.tvPubPlaceCharter2);
			final String strMarket = marketDistricts.get(i).getDistrict();
			textView.setText(strMarket);

			textView.setOnTouchListener(new OnTouchListener() {
				@Override
				public boolean onTouch(View arg0, MotionEvent arg1) {
					// TODO Auto-generated method stub
					llSearchSupTip.setVisibility(View.GONE);
					return false;
				}
			});
			textView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(getBaseContext(),
							PurSupplierSearchShowActivity.class);
					intent.putExtra("city", cityString);
					intent.putExtra("market", strMarket);
					intent.putExtra("searchFormText", false);
					startActivity(intent);
				}
			});

			marketItem.removeAllViews();
			llSearchSupMarket.addView(textView);
		}
	}

	/**
	 * 输入框编辑监听
	 */
	TextWatcher myTextWatcher = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			// TODO Auto-generated method stub
		}

		@Override
		public void afterTextChanged(Editable arg0) {
			// TODO Auto-generated method stub
			llSearchSupTip.removeAllViews();
			strSearchText = etSearchText.getText().toString();
			if (strSearchText != null && !strSearchText.equals("")) {
				tips.clear();
				tips.add(strSearchText);
				loadType = 0;
				normalDataLoader.load();
			}
		}
	};

	OnClickListener myClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.ivPublicTitleReturn:
				CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_SUPPLIER;
				Intent intent = new Intent(getBaseContext(),
						CargoActivity.class);
				startActivity(intent);
				PurSupplierSearchActivity.this.finish();
				break;

			default:
				break;
			}
		}
	};

	OnClickListener ivGPSclick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			PurMapActivity.LAUNCH_MODE = PurMapActivity.MY_LOC_AND_SUPLIST;
			Intent intent = new Intent(PurSupplierSearchActivity.this,
					PurMapActivity.class);
			startActivity(intent);
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_SUPPLIER;
			Intent intent = new Intent(getBaseContext(), CargoActivity.class);
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub

	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		GsonBean gsonBean = null;
		switch (loadType) {
		case 0:
			gsonBean = searchSupplierTipsService.execute(0, 10, strSearchText);
			if (CheckStateUtil.check(gsonBean)) {
				List<String> tipList = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<String>>() {
						}.getType());
				tips.addAll(tipList);
			}
			msg.what = MyStateUtil.SEARCH_TIP_SHOW;
			break;
		case 1:
			gsonBean = getCityService.execute(0, 100);
			if (CheckStateUtil.check(gsonBean)) {
				List<District> districts = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<District>>() {
						}.getType());
				cityDistricts.addAll(districts);
			}
			msg.what = MyStateUtil.SEARCH_CITY_SHOW;
			break;
		case 2:
			gsonBean = getMarketService.execute(cityString, 0, 100);
			if (CheckStateUtil.check(gsonBean)) {
				List<District> districts = DataUtil.gson.fromJson(
						gsonBean.getStrJson(), new TypeToken<List<District>>() {
						}.getType());
				marketDistricts.addAll(districts);
			}
			msg.what = MyStateUtil.SEARCH_MARKET_SHOW;
			break;
		default:
			break;
		}
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		llSearchSupTip.removeAllViews();
		switch (state) {
		case MyStateUtil.SEARCH_TIP_SHOW:
			llSearchSupTip.setVisibility(View.VISIBLE);
			showTip();
			break;
		case MyStateUtil.SEARCH_CITY_SHOW:
			llSearchSupCity.setVisibility(View.VISIBLE);
			showCity();
			break;
		case MyStateUtil.SEARCH_MARKET_SHOW:
			showMarket();
			break;
		default:
			break;
		}
	}

}
